import Frame from "../frameNamespace";
import { GAME_MODE } from "../other/game/gameMode_Json";
import cebianlan from "../other/page/cebianlan";
import Dialog from "../other/page/dialog";
import Fuwu from "../other/page/Fuwu";
import gameList from "../other/page/gameList";
import gameListNew from "../other/page/gameListNew";
import GameSettingPage from "../other/page/gameSettingPage";
import GetPowerPage from "../other/page/getPowerPage";
import InfinityPowerPage from "../other/page/infinityPowerPage";
import LoadingPage from "../other/page/loadingPage";
import Message from "../other/page/message";
import ModeSelect from "../other/page/ModeSelect";
import PageBase from "../other/page/pageBase";
import selectArea from "../other/page/selectArea";
import SignIn from "../other/page/SignIn";
import tianjiazhuomian from "../other/page/tianjiazhuomian";
import tishi from "../other/page/tishi";
import YInsi from "../other/page/Yinsi";
import zhutiList from "../other/page/zhutiList";
import UMe, { mgrs, sers } from "../system/OverallSystem ";
import UserService from "./userService";

enum DeviceOrientation {
    portrait,
    landscape,
}

export default class UIService extends Frame.ServiceBase {
    protected _serviceName: string = "ui服务";

    constructor() {
        super();

        this._Initialize();
    }

    _Initialize(): void {
        super._Initialize();

        this.framePagePrefix = (this._deviceOrientation == DeviceOrientation.portrait ? "portrait/" : "landscape/");
    }

    private uiRoot: cc.Node = null;
    get UIRoot() { return this.uiRoot; }
    _setUIRoot(uiR: cc.Node) { this.uiRoot = uiR; }

    private _pageList: PageBase[] = [];

    private framePagePrefix: string = "landscape/";

    /** 设备方向 */
    private _deviceOrientation: DeviceOrientation = DeviceOrientation.landscape;
    /** 设备方向 */
    get deviceOrientation() { return this._deviceOrientation; }
    /** 设备方向 */
    set deviceOrientation(dir: DeviceOrientation) { this._deviceOrientation = dir; }

    /**
     * 打开页面初始化，页面通常最多同时存在两个
     * @param component 传入页面基础组件
     * @param isSingle 是否只显示这个
     * @param isCeiling 是否有显示两个页面的上限
     */
    private openPageInit(component: PageBase, isSingle: boolean = false, isCeiling: boolean = true) {
        if (isSingle) {
            this._pageList.forEach((elem) => {
                elem.onlyClose();
            });
            this._pageList = [];
        }

        this._pageList.push(component);

        while (isCeiling && this._pageList.length > 2) {
            this._pageList.shift().onlyClose();
        }

        for (let i = 0; i < this._pageList.length; i++) {
            this._pageList[i].id = i;
        }

        console.log("添加页面入表 >>>> ", component.pageName);
    }

    deletePageRecord(id: number) {
        this._pageList.splice(id, 1);

        for (let i = 0; i < this._pageList.length; i++) {
            this._pageList[i].id = i;
        }
    }

    _closeCurrScenePage() {

        // console.debug("-01", this._pageList);

        this._pageList.forEach((elem) => {
            if (elem.node) {
                elem.node.destroy();
            }
        });

        this._pageList = [];

        // console.debug("-02", this._pageList); 
    }

    /**
     * 弹出对话框
     * @param message 文字内容
     * @param title 标题
     * @param colseDoFun 关闭回调
     * @param parentNode 页面父节点
     * @param isVideoAd 是否需要视频广告
     * @param videoAdCnt 看视频广告次数
     * @param videoAdCB 看视频广告回调
     * @param isSingle 是否只显示这个
     * @param isCeiling 是否有显示两个页面的上限
     * @param lookVideoSource 看视频广告目的，未实装打点
     */
    showDialog(message: string, title: string = "温馨提示",
        colseDoFun?: () => void, parentNode?: cc.Node,
        isVideoAd: boolean = false, videoAdCnt: number = 0,
        videoAdCB?: () => void, isSingle: boolean = false, isCeiling: boolean = true, lookVideoSource?: string) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "dialog";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: Dialog = newPage.getComponent(Dialog);
            pageScript.setDate(message, title, colseDoFun, isVideoAd, videoAdCnt, videoAdCB, lookVideoSource);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

    /**
     * 弹出游戏设置页面
     * @param parentNode 页面父节点
     * @param isSingle 是否只显示这个
     * @param isCeiling 是否有显示两个页面的上限 
     */
    showSettingPage(showBtn=0, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "gameSetting";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: GameSettingPage = newPage.getComponent(GameSettingPage);
            pageScript.showBtn(showBtn)
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

    // showShoppingPage(cb?: () => void, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
    //     parentNode = parentNode || this.uiRoot;
    //     const path: string = this.framePagePrefix + "Shopping";

    //     this.loadPagePrefab(path).then((pf: cc.Prefab) => {
    //         const newPage: cc.Node = cc.instantiate(pf);
    //         const pageScript: Shopping = newPage.getComponent(Shopping);
    //         // pageScript.setCloseDoFun(cb);
    //         this.openPageInit(pageScript, isSingle, isCeiling);
    //         parentNode.addChild(newPage);
    //     });
    // }

    /**
     * 弹出隐私确认设置页面
     * @param parentNode 页面父节点
     * @param isSingle 是否只显示这个
     * @param isCeiling 是否有显示两个页面的上限 
     */
    showTipsPage(parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "tishi";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: tishi =  newPage.getComponent(tishi);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

    showYinsiPage(parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "Yinsi";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: YInsi =  newPage.getComponent(YInsi);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

    showtianjiazhuomianPage(parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "tianjiazhuomian";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: tianjiazhuomian =  newPage.getComponent(tianjiazhuomian);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

    showFuwuPage(parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "Fuwu";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: Fuwu =  newPage.getComponent(Fuwu);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

    showGameListNewPage(cb?: () => void, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "gameListNew";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: gameListNew = newPage.getComponent(gameListNew);
            pageScript.setCloseDoFun(cb);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

    showModeSelectPage(cb?: () => void, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "ModeSelect";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: ModeSelect = newPage.getComponent(ModeSelect);
            pageScript.setCloseDoFun(cb);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }


     /**
     * 弹出游戏过关页面
     * @param parentNode 页面父节点
     * @param isSingle 是否只显示这个
     * @param isCeiling 是否有显示两个页面的上限
     */
     showOverPage(data?,cb?: Function, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "OverPage";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: PageBase = newPage.getComponent(PageBase);
            this.openPageInit(pageScript, isSingle, isCeiling);
            pageScript.setCloseDoFun(cb);
            pageScript.initData(data)
            parentNode.addChild(newPage);
        });
    }


    showTyOverPage(data?,cb?: Function, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "TyOverPage";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: PageBase = newPage.getComponent(PageBase);
            this.openPageInit(pageScript, isSingle, isCeiling);
            pageScript.setCloseDoFun(cb);
            pageScript.initData(data)
            parentNode.addChild(newPage);
        });
    }


    showCebianlan(parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "cebianlan";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: cebianlan =  newPage.getComponent(cebianlan);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

     /** 弹出选地区的界面 */
     showSelectDiQuPage(data?, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "selectArea";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: selectArea = newPage.getComponent(selectArea);
            pageScript.pageData = data;
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

     /** 弹出排行榜的界面 */
     showRankingListPage(data?, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "rankingList";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: PageBase = newPage.getComponent(PageBase);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

    showGameListPage(cb?: () => void, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "gameList";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: gameList = newPage.getComponent(gameList);
            pageScript.setCloseDoFun(cb);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

    showZhutiListPage(cb?: () => void, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "zhutiList";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: zhutiList = newPage.getComponent(zhutiList);
            // pageScript.setCloseDoFun(cb);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

    showSignInPage(cb?: () => void, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "SignIn";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: SignIn = newPage.getComponent(SignIn);
            // pageScript.setCloseDoFun(cb);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }
    

    /**
     * 弹出无限体力页面
     * @param parentNode 页面父节点
     * @param isSingle 是否只显示这个
     * @param isCeiling 是否有显示两个页面的上限
     */
    showInfinityPage(clsoeCB?: (bool: boolean) => void, receiveCB?: (bool: boolean) => void, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        let isInfinityPowerModel = Number(sers().localStorageSrv.get(UserService.infinityPowerModel)) != 0;
        if (isInfinityPowerModel) {
            clsoeCB && clsoeCB(false);
            return;
        }
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "infinityPower";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: InfinityPowerPage = newPage.getComponent(InfinityPowerPage);
            pageScript.setCloseDoFun(clsoeCB);
            pageScript.setCloseDoFun2(receiveCB);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

    /**
     * 弹出确认无限体力页面
     * @param parentNode 页面父节点
     * @param isSingle 是否只显示这个
     * @param isCeiling 是否有显示两个页面的上限
     */
    showReceiveInfinityPage(cb?: Function, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = true) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "receiveInfinit";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: PageBase = newPage.getComponent(PageBase);
            this.openPageInit(pageScript, isSingle, isCeiling);
            pageScript.setCloseDoFun(cb);
            parentNode.addChild(newPage);
        });
    }

    /**
     * 弹出获取体力页面
     * @param parentNode 页面父节点
     * @param isSingle 是否只显示这个
     * @param isCeiling 是否有显示两个页面的上限
     */
    showUserGetPowerPage(cb?: () => void, parentNode?: cc.Node, isSingle: boolean = false, isCeiling: boolean = false) {
        parentNode = parentNode || this.uiRoot;
        const path: string = this.framePagePrefix + "getPower";

        this.loadPagePrefab(path).then((pf: cc.Prefab) => {
            const newPage: cc.Node = cc.instantiate(pf);
            const pageScript: GetPowerPage = newPage.getComponent(GetPowerPage);
            pageScript.setCloseDoFun(cb);
            this.openPageInit(pageScript, isSingle, isCeiling);
            parentNode.addChild(newPage);
        });
    }

    /**
     * 弹出一条消息
     * @param text 消息内容
     * @param delay 消息存在时间
     * @param parentNode 父节点
     */
    showMessage(text: string, delay: number = 2, parentNode?: cc.Node) {
        parentNode = parentNode || this.uiRoot;

        this.loadPagePrefab("message").then((pf: cc.Prefab) => {
            const newMessage: cc.Node = cc.instantiate(pf);
            const messageScript = newMessage.getComponent(Message);
            messageScript.setData(text, delay);
            parentNode.addChild(newMessage);
            newMessage.zIndex = cc.macro.MAX_ZINDEX;
        });
    }

    private loadingPage: LoadingPage = null;
    showLoding(init = false) {
        this.hideLoding()
        if(this.loadingPage && this.loadingPage.node.parent){
            this.loadingPage.node.active = true
        }else{
            this.loadPagePrefab2("loading").then((pf: cc.Prefab) => {
                const newPage: cc.Node = cc.instantiate(pf);
                this.loadingPage = newPage.getComponent(LoadingPage);
                this.uiRoot.addChild(newPage);
                if(init){
                    this.hideLoding()
                }
            });
        }
       
    }

    hideLoding() {
        if (this.loadingPage != null) {
            // this.loadingPage.close();
            // this.loadingPage = null;
            this.loadingPage.node.active = false
        }
    }

    private loadPagePrefab(path: string) {
        return new Promise<cc.Prefab>((resolve, reject) => {
            mgrs().bundleMgr.BundleList.frameBundle.load("framePrefab/" + path, cc.Prefab, (error: Error, pf: cc.Prefab) => {
                if (error) {
                    console.error("从bundle加载页面预制体出错 :", path, "-----", error);
                    reject();
                    return;
                }
                resolve(pf);
            });
        });
    }

    private loadPagePrefab2(path: string) {
        return new Promise<cc.Prefab>((resolve, reject) => {
            mgrs().bundleMgr.BundleList.loadingPage.load("framePrefab/" + path, cc.Prefab, (error: Error, pf: cc.Prefab) => {
                if (error) {
                    console.error("从bundle加载页面预制体出错 :", path, "-----", error);
                    reject();
                    return;
                }
                resolve(pf);
            });
        });
    }

    /**
     * 打开页面基础动画
     * @param node 操作节点
     * @param isActiveNode 是否激活节点，默认为 false
     * @returns Promise<void>
     */
    static openPageBasicAni(node: cc.Node, isActiveNode: boolean = false) {
        return new Promise<void>((resolve, reject) => {
            if (node == null || !node.isValid) {
                console.error("openPageBasicAni 节点为空 或 不可用");
                reject();
                return;
            }
            if (!isActiveNode && !node.active) {
                console.error("openPageBasicAni 节点未激活");
                reject();
                return;
            }
            if (isActiveNode) {
                node.active = true;
            }
            node.scale = 0.01;
            // node.y -= 50;
            node.opacity = 0;
            cc.tween(node)
                .parallel(
                    cc.tween(node).to(0.15, { opacity: 255 }),
                    cc.tween(node).to(0.2, { scale: 1 },cc.easeBackOut()),
                    cc.tween(node).by(0.2, { y: 0 }),
                )
                .call(() => {
                    resolve();
                })
                .start();
        });
    }

    static openPageBasicAni2(node: cc.Node, isActiveNode: boolean = false) {
        return new Promise<void>((resolve, reject) => {
            if (node == null || !node.isValid) {
                console.error("openPageBasicAni 节点为空 或 不可用");
                reject();
                return;
            }
            if (!isActiveNode && !node.active) {
                console.error("openPageBasicAni 节点未激活");
                reject();
                return;
            }
            if (isActiveNode) {
                node.active = true;
            }
            node.scale = 0.01;
            // node.y -= 50;
            node.opacity = 0;

            if(node.children[0]){
                node.children[0].active=false
            }
            cc.tween(node)
                .parallel(
                    cc.tween(node).to(0.15, { opacity: 255 }),
                    cc.tween(node).to(0.2, { scale: 1 },cc.easeBackOut()),
                    cc.tween(node).by(0.2, { y: 0 }),
                )
                .call(() => {
                    if(node.children[0]){
                        node.children[0].active=true
                        node.children[0].opacity = 0
                        cc.tween(node.children[0]).to(0.3,{opacity:180}).start()
                    }
                    
                    resolve();
                })
                .start();
        });
    }

    /**
     * 关闭页面基础动画
     * @param node 操作节点
     * @param isResume 是否还原动画改变的属性
     * @returns Promise<void>
     */
    static closePageBasicAni(node: cc.Node, isResume: boolean = false,hide:boolean=false) {
        return new Promise<void>((resolve, reject) => {
            if (node == null || !node.isValid) {
                console.error("closePageBasicAni 节点为空 或 不可用");
                reject();
                return;
            }
            if (!node.active) {
                console.error("closePageBasicAni 节点未激活");
                reject();
                return;
            }
            cc.tween(node)
                .parallel(
                    cc.tween(node).to(0.2, { scale: 0.01 },cc.easeInOut(3.0)),
                    cc.tween(node).by(0.2, { y: -50 }),
                    cc.tween(node).delay(0.1).to(0.1, { opacity: 0 }),
                )
                .call(() => {
                    resolve();
                    if (isResume) {
                        node.scale = 1;
                        // node.y += 50;
                    }
                    if(hide){
                        node.active=false
                    }
                })
                .start();
        });
    }

    static closePageBasicAni2(node: cc.Node, isResume: boolean = false,hide:boolean=false) {
        return new Promise<void>((resolve, reject) => {
            if (node == null || !node.isValid) {
                console.error("closePageBasicAni 节点为空 或 不可用");
                reject();
                return;
            }
            if (!node.active) {
                console.error("closePageBasicAni 节点未激活");
                reject();
                return;
            }
            if(node.children[0]){
                cc.tween(node.children[0]).to(0.1,{opacity:0}).call(()=>{
                    node.children[0].active=false
                }).start()
            }
            cc.tween(node)
                .parallel(
                    cc.tween(node).to(0.2, { scale: 0.01 },cc.easeInOut(3.0)),
                    cc.tween(node).by(0.2, { y: 0 }),
                    cc.tween(node).delay(0.1).to(0.1, { opacity: 0 }),
                )
                .call(() => {
                    resolve();
                    if (isResume) {
                        node.scale = 1;
                        // node.y += 50;
                    }
                    if(hide){
                        node.active=false
                    }

                })
                .start();
        });
    }
}